import time
import socket
from gevent import monkey
monkey.patch_all()
import gevent
import gevent.pool
import os

class Scan_ip(object):
    #读取文件
    def read_file(self):
        data = []
        with open(os.path.abspath('.') + '\config_data\data.txt', 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                data.append(line.strip())
        str_ip = ''.join(data)
        ip_list = str_ip.split('",')
        dit_ip = {}
        for i in ip_list:
            dit_ip[i.split(': "')[0]] = i.split(': "')[1]
        return dit_ip

    def TCP_connect(self,ip,port):
        dit_ip = self.read_file()
        """模拟TCP连接"""
        TCP_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置连接超时
        TCP_sock.settimeout(0.5)
        try:
            result = TCP_sock.connect_ex((ip, int(port)))
            if result == 0:
                if str(port) in dit_ip:
                    print("[*]{}端口开启,{}".format(port,dit_ip[str(port)]))
                else:
                    print("[*]{}端口开启,端口特性未知?".format(port))
            else:
                pass
            TCP_sock.close()
        except socket.error as e:
            print("[!]错误:", e)

    def scan_ip(self):
        """扫描目标IP"""
        ip = input("[+]输入扫描目标IP:")
        num = int(input("[+]请输入扫描的范围:"))
        print("[*]开始扫描目标端口......")
        start = time.time()
        # 设置线程数
        g = gevent.pool.Pool(50)
        run_list = []
        for port in range(1, num):
            run_list.append(g.spawn(self.TCP_connect, ip, port))
        gevent.joinall(run_list)
        end = time.time()
        print("[*]总耗时%s" % time.strftime("%H:%M:%S", time.gmtime(end - start)))

if __name__ == "__main__":
    Scan_ip().scan_ip()
